import React,{useEffect,useState}from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Button, Card, Input, Form, InputNumber, Select,Radio,Divider,Col,DatePicker,Descriptions,Tag,message } from 'antd';
import { connect ,history} from 'umi';
import db from '@/utils/localstorage';
import Contanst from '@/config/contanst'
import Yuan from '@/utils/Yuan';
import moment from 'moment';
import {memberRenewCard} from '../service';
const FormItem = Form.Item;
const { TextArea } = Input;
const formItemLayout = {
    labelCol: {
      xs: {
        span: 24,
      },
      sm: {
        span: 5,
      },
    },
    wrapperCol: {
      xs: {
        span: 24,
      },
      sm: {
        span: 15,
      },
      md: {
        span: 15,
      },
    },
  };
  const submitFormLayout = {
    wrapperCol: {
      xs: {
        span: 24,
        offset: 0,
      },
      sm: {
        span: 10,
        offset: 5,
      },
    },
  };
const RenewCard = props =>{
    const {dispatch,vipCard,shopList,salesList,match} =props;
    const [form] = Form.useForm();
    const [dictTypeList, setDictTypeList] = useState(db.get("dictTypeList")['payment_method']);
    const [durationDaysMaturity, setDurationDaysMaturity] = useState("");
    const [storedValueAmountMaturity, setStoredValueAmountMaturity] = useState("");
    const [recharge, setRecharge] = useState("");
    useEffect(() => {
        if (dispatch) {
            dispatch({
                type: 'cubeVipCardOper/fetchShopList',
                payload:{
                  userId:db.get("user").userId
                }
              })
        
              dispatch({
                type: 'cubeVipCardOper/fetchSalesList',
                payload:{
                  userId:db.get("user").userId
                }
              })
              dispatch({
                type: 'cubeVipCardOper/getMemberCardInfo',
                payload:{
                    cardId:match.params.cardId,
                    memberId:match.params.memberId
                }
              })
         }
       }, []);
    /**
     *  保存
     * @param {*} values 
     */
    const onFinish = async () =>{
      const hide = message.loading('正在续卡');
      const values = await form.validateFields();
      if(vipCard.cardType=='1'){
        if(values.storedValueAmount=='customize'){
          values.storedValueAmount = values.storedValueAmountMaturity
        }else{
          let settingPriceGradientDTOList = vipCard.settingPriceGradientDTOList;
          let _settingPriceGradientDTOList = settingPriceGradientDTOList.filter((item)=>item.id==values.storedValueAmount);
          let settingPriceGradientDTO;
          if(_settingPriceGradientDTOList&&_settingPriceGradientDTOList.length>0){
            settingPriceGradientDTO=_settingPriceGradientDTOList[0]
            values.storedValueAmount = settingPriceGradientDTO.storedValueAmount
          }
        }
      }else if(vipCard.cardType=='2'){
        if(values.recharge != 'customize'){
          let settingPriceGradientDTOList = vipCard.settingPriceGradientDTOList;
          let _settingPriceGradientDTOList = settingPriceGradientDTOList.filter((item)=>item.id==values.recharge);
          let settingPriceGradientDTO;
          if(_settingPriceGradientDTOList&&_settingPriceGradientDTOList.length>0){
            settingPriceGradientDTO=_settingPriceGradientDTOList[0]
            values.numberPrivateTeaching = settingPriceGradientDTO.numberPrivateTeaching
            values.numberGroupLessons = settingPriceGradientDTO.numberGroupLessons
            values.numberSmallClasses = settingPriceGradientDTO.numberSmallClasses
          }
        }
      }else if(vipCard.cardType=='3'){
        if(values.cardOpeningTime != '1'){
          values.cardOpeningTime = moment(values.cardOpeningTime).format('YYYY-MM-DD')
        }
        if(values.durationDays=='customize'){
          values.durationDays = values.durationDaysMaturity
        }else{
          let settingPriceGradientDTOList = vipCard.settingPriceGradientDTOList;
          let _settingPriceGradientDTOList = settingPriceGradientDTOList.filter((item)=>item.id==values.durationDays);
          let settingPriceGradientDTO;
          if(_settingPriceGradientDTOList&&_settingPriceGradientDTOList.length>0){
            settingPriceGradientDTO=_settingPriceGradientDTOList[0]
            values.durationDays = settingPriceGradientDTO.durationDays
          }
        }
      }
      try {
        let result = await memberRenewCard({
          cardId:vipCard.cardId,
          memberId:vipCard.memberId,
          cardType:vipCard.cardType,
          ...values
        });
        hide();
        if(result.code ==0){
          message.success('续卡成功，即将跳转');
          history.push(`/vip/bind-card`);
          return true;
        }else{
          message.error(result.message);
          return false; 
        }
      } catch (error) {
        hide();
        message.error('续卡失败，请重试');
        return false;
      }
    }

    const storedValueAmountChange = e =>{
      let value = e.target.value;
      setStoredValueAmountMaturity(value);
      if(value != 'customize'){
        let settingPriceGradientDTOList = vipCard.settingPriceGradientDTOList;
        let _settingPriceGradientDTOList = settingPriceGradientDTOList.filter((item)=>item.id==value);
        let settingPriceGradientDTO;
        if(_settingPriceGradientDTOList&&_settingPriceGradientDTOList.length>0){
          settingPriceGradientDTO=_settingPriceGradientDTOList[0]
          form.setFieldsValue({
            paidInAmount:settingPriceGradientDTO.sellingPrice
          })
        }
      }
    }

    const numberChange = e =>{
      let value = e.target.value;
      setRecharge(value)
      if(value != 'customize'){
        let settingPriceGradientDTOList = vipCard.settingPriceGradientDTOList;
        let _settingPriceGradientDTOList = settingPriceGradientDTOList.filter((item)=>item.id==value);
        let settingPriceGradientDTO;
        if(_settingPriceGradientDTOList&&_settingPriceGradientDTOList.length>0){
          settingPriceGradientDTO=_settingPriceGradientDTOList[0]
          form.setFieldsValue({
            paidInAmount:settingPriceGradientDTO.sellingPrice
          })
        }
      }
    }

    const durationDaysChange = e =>{
      let value = e.target.value;
      setDurationDaysMaturity(value)
      if(value != 'customize'){
        let settingPriceGradientDTOList = vipCard.settingPriceGradientDTOList;
        let _settingPriceGradientDTOList = settingPriceGradientDTOList.filter((item)=>item.id==value);
        let settingPriceGradientDTO;
        if(_settingPriceGradientDTOList&&_settingPriceGradientDTOList.length>0){
          settingPriceGradientDTO=_settingPriceGradientDTOList[0]
          form.setFieldsValue({
            paidInAmount:settingPriceGradientDTO.sellingPrice
          })
        }
      }
    }
    return <PageHeaderWrapper>
        <Card title="会员卡信息" style={{marginBottom:32}}>
        <Descriptions size="small">
            <Descriptions.Item label="会员"><a onClick={()=>go2VipDetail()}>{vipCard.memberName}</a></Descriptions.Item>
            <Descriptions.Item label="会员卡类型">{Contanst.MemberCardTypeMap[vipCard.cardType]}</Descriptions.Item>
            <Descriptions.Item label="会员卡名称">{vipCard.cardName}</Descriptions.Item>
            <Descriptions.Item label="会员卡创建时间">{vipCard.createTime}</Descriptions.Item>
            <Descriptions.Item label="当前状态"><Tag>{Contanst.CardBindStatusMap[vipCard.cardStatus]}</Tag></Descriptions.Item>
            {
                vipCard.cardType=='3'&&<>
                    <Descriptions.Item label="有效期">{vipCard.periodValidity}</Descriptions.Item>
                    <Descriptions.Item label="剩余天数">{vipCard.balance}</Descriptions.Item>
                 </>
            }
            {
                 vipCard.cardType=='2'&&<>
                    <Descriptions.Item label="有效期">{vipCard.periodValidity}</Descriptions.Item>
                    <Descriptions.Item label="剩余次数">{vipCard.balance}</Descriptions.Item>
                 </>
            }
            {
                 vipCard.cardType=='1'&&<>
                    <Descriptions.Item label="有效期">{vipCard.periodValidity}</Descriptions.Item>
                    <Descriptions.Item label="剩余金额">{vipCard.balance}</Descriptions.Item>
                 </>
            }
            <Descriptions.Item label="累计实收金额"><Yuan>{vipCard.totalMoney}</Yuan></Descriptions.Item>
            <Descriptions.Item label="开卡场馆">{vipCard.venueName}</Descriptions.Item>
            <Descriptions.Item label="备注">{vipCard.zb}</Descriptions.Item>
          </Descriptions>
        </Card>
        <Card title="会员卡充值">
            <Form style={{
                    marginTop: 8,
                }}
                form={form}
                name="basic"
                >
                {
                  vipCard.cardType=='1'&&<><FormItem
                  {...formItemLayout}
                  label="充值元数"
                  name="storedValueAmount"
                  rules={[
                    {
                      required: true,
                      message: '请输入充值元数',
                    },
                  ]}
                >
                   <Radio.Group onChange={storedValueAmountChange}>
                      {
                        vipCard.settingPriceGradientDTOList&&vipCard.settingPriceGradientDTOList.map((item,index)=><Col span={24} key={index}><Radio key={index} value={item.id}>
                          <span>储值金额：{item.storedValueAmount}元</span> <Divider type="vertical" />
                          <span>{item.sellingPrice}元</span>
                        </Radio></Col>)
                      }
                      <Col span={24}><Radio value="customize">自定义金额</Radio></Col>  
                   </Radio.Group>
                </FormItem>
                {
                    storedValueAmountMaturity=='customize'&&<FormItem
                    {...formItemLayout}
                    label="储值金额/元"
                    name="storedValueAmountMaturity"
                  >
                      <InputNumber
                      min={0}
                      style={{width:'100%'}}
                    />
                  </FormItem>
                  }
                </>
                }
                {
                  vipCard.cardType=='2'&&<>
                    <FormItem
                      {...formItemLayout}
                      label="充值次数"
                      name="recharge"
                      rules={[
                        {
                          required: true,
                          message: '请输入充值次数',
                        },
                      ]}
                    >
                      <Radio.Group onChange={numberChange}>
                          {
                            vipCard.settingPriceGradientDTOList&&vipCard.settingPriceGradientDTOList.map((item,index)=><Col span={24}><Radio key={index} value={item.id}>
                              <span>私教次数：{item.numberPrivateTeaching}次</span> <Divider type="vertical" /><span>团课次数：{item.numberGroupLessons}次</span> <Divider type="vertical" /><span>小班次数：{item.numberSmallClasses}次</span>
                              <Divider type="vertical" /><span>{item.sellingPrice}元</span> <Divider type="vertical" /><span>{item.periodValidity}天内有效</span>
                            </Radio></Col>)
                          }
                          <Col span={24}><Radio value="customize">自定义次数</Radio> </Col> 
                      </Radio.Group>
                    </FormItem>
                    {
                      recharge=='customize'&&<>
                      <FormItem
                        {...formItemLayout}
                        label="私教次数/次"
                        name="numberPrivateTeaching"
                      >
                          <InputNumber
                          placeholder="请输入自定义私教次数"
                          min={0}
                          style={{width:'100%'}}
                        />
                      </FormItem>
                      <FormItem
                        {...formItemLayout}
                        label="大班次数/次"
                        name="numberGroupLessons"
                      >
                          <InputNumber
                          placeholder="请输入自定义大班次数"
                          min={0}
                          style={{width:'100%'}}
                        />
                      </FormItem>
                      <FormItem
                        {...formItemLayout}
                        label="小班次数/次"
                        name="numberSmallClasses"
                      >
                          <InputNumber
                          placeholder="请输入自定义小班次数"
                          min={0}
                          style={{width:'100%'}}
                        />
                      </FormItem>
                  </>
                  }
                  </>
                }
                 {
                    vipCard.cardType=='3'&&<>
                    {
                      (vipCard&&vipCard.cardSuperSettingsDTO&&vipCard.cardSuperSettingsDTO.isFirstClassOpenCard=='1')?
                        <FormItem
                        {...formItemLayout}
                        label="开始时间"
                        name="cardOpeningTime"
                        rules={[
                          {
                            required: true,
                            message: '请选择开始时间',
                          },
                        ]}
                      >
                        <Select style={{ width: '100%' }} placeholder="请选择" disabled>
                          <Select.Option value="1">第一次上课开卡</Select.Option>
                        </Select>
                      </FormItem>:
                      <FormItem
                      {...formItemLayout}
                      label="开始时间"
                      name="cardOpeningTime"
                      rules={[
                        {
                          required: true,
                          message: '请选择开始时间',
                        },
                      ]}
                    >
                      <DatePicker style={{width:'100%'}}/>
                    </FormItem>
                    }
                    <FormItem
                      {...formItemLayout}
                      label="充值天数"
                      name="durationDays"
                      rules={[
                        {
                          required: true,
                          message: '请输入充值元数',
                        },
                      ]}
                    >
                        <Radio.Group onChange={durationDaysChange}>
                          {
                            vipCard.settingPriceGradientDTOList&&vipCard.settingPriceGradientDTOList.map((item,index)=><Col span={24}><Radio key={index} value={item.id}>
                              <span>期限天数：{item.durationDays}天</span> <Divider type="vertical" />
                              <span>{item.sellingPrice}元</span>
                            </Radio></Col>)
                          }
                          <Col span={24}><Radio value="customize">自定义天数</Radio></Col> 
                      </Radio.Group>
                    </FormItem>
                    {
                      durationDaysMaturity=='customize'&&<FormItem
                      {...formItemLayout}
                      label="期限天数/天"
                      name="durationDaysMaturity"
                    >
                        <InputNumber
                         placeholder="请输入期限天数"
                        min={0}
                        style={{width:'100%'}}
                      />
                    </FormItem>
                    }
                    </>
                  }
                <FormItem
                    {...formItemLayout}
                    label="实收金额"
                    name="paidInAmount"
                    rules={[
                    {
                        required: true,
                        message: '请输入实收金额',
                    },
                    ]}
                >
                    <InputNumber
                    min={0}
                    style={{width:'100%'}}
                    formatter={value => `${value}元`}
                    parser={value => value.replace('元', '')}
                    />
                </FormItem>
                <FormItem
                {...formItemLayout}
                label="支付模式"
                name="paymentMethod"
                rules={[
                {
                    required: true,
                    message: '请选择支付模式',
                },
                ]}
            >
                <Select style={{ width: '100%' }} placeholder="请选择">
                {
                    dictTypeList&&dictTypeList.map((item,index)=><Select.Option key={index} value={item.value}>{item.label}</Select.Option>)
                }
                </Select>
            </FormItem>
            <FormItem
                {...formItemLayout}
                label="续卡场馆"
                name="venueId"
                rules={[
                {
                    required: true,
                    message: '请选择续卡场馆',
                },
                ]}
            >
                <Select style={{ width: '100%' }} placeholder="请选择">
                {
                    shopList&&shopList.map((item,index)=> <Select.Option value={item.id} key={index}>{item.name}</Select.Option>)
                }
                </Select>
            </FormItem>
            <FormItem
                {...formItemLayout}
                label="销售人员"
                name="salesStaffId"
            >
                <Select style={{ width: '100%' }} placeholder="请选择">
                {
                    salesList&&salesList.map((item,index)=><Select.Option value={item.userId} key={index}>{item.name}</Select.Option>)
                }
                </Select>
            </FormItem>
            <FormItem
                {...formItemLayout}
                label="备注信息"
                name="zb"
            >
                <TextArea rows={4} placeholder="请输入"/>
            </FormItem>
            <FormItem
                {...submitFormLayout}
                style={{
                marginTop: 32,
                }}
            >
                <Button type="primary" onClick={onFinish}>
                提交
                </Button>
                <Button
                style={{
                    marginLeft: 8,
                }}
                onClick={()=>window.history.back()}
                >
                返回
                </Button>
            </FormItem>
            </Form>
        </Card>
    </PageHeaderWrapper>
}

export default connect(({ loading,cubeVipCardOper }) => ({
    vipCard: cubeVipCardOper.vipCard,
    shopList:cubeVipCardOper.shopList,
    salesList:cubeVipCardOper.salesList
  }))(RenewCard);